package com.wejoy.video.middle.station.data.service.common.impl;


import com.wejoy.video.middle.station.data.exception.BusinessException;
import com.wejoy.video.middle.station.data.service.common.IDictService;
import com.wejoy.video.middle.station.data.vo.dict.DictVO;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 字典业务类
 *
 * @author admin
 */
@Service
public class DictServiceImpl implements IDictService {
    /**
     * 所有的新枚举都在这个包下
     */
    String DICT_BASE_PACKAGE = "com.wejoy.video.middle.station.data.enums.dict";


    @Override
    public List<DictVO> getDictData(String name) {
        return getEnumDict(name);
    }

    /**
     * 通过枚举名称获得枚举数据
     *
     * @param name 枚举名称, 注意枚举必须放在DICT_BASE_PACKAGE下面
     * @return
     */
    private List<DictVO> getEnumDict(String name) {
        String className = DICT_BASE_PACKAGE + "." + name;
        Method method;
        try {
            method = Class.forName(className).getMethod("values");
        } catch (NoSuchMethodException e) {
            throw new BusinessException("枚举类反射异常：不存在的方法！method=values");
        } catch (ClassNotFoundException e) {
            throw new BusinessException(String.format("枚举类反射异常：不存在的枚举类！className=%s", className));
        }
        try {
            Object invoke = method.invoke(null);
            Object[] list = (Object[]) invoke;
            List<DictVO> voList = new ArrayList<>();
            for (Object o : list) {
                Object enumCode = o.getClass().getMethod("getCode").invoke(o);
                String enumText = o.getClass().getMethod("getText").invoke(o).toString();
                DictVO vo = new DictVO(enumCode.toString(), enumText);
                voList.add(vo);
            }
            return voList;
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new BusinessException(String.format("枚举类反射异常：方法[%s]执行失败！", method.getName()));
        } catch (NoSuchMethodException e) {
            throw new BusinessException(String.format("枚举类反射异常：方法[%s]不存在！", method.getName()));
        }
    }
}
